package com.csproj.system.resource;

import com.codahale.metrics.annotation.Timed;

import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.system.repository.AuthorityInfoRepository;
import com.csproj.system.service.AuthorityInfoService;
import com.csproj.system.service.dto.AuthorityInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing AuthorityInfo.
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class AuthorityInfoResource {

    private final Logger log = LoggerFactory.getLogger(AuthorityInfoResource.class);

    private static final String ENTITY_NAME = "authorityInfo";

    private final AuthorityInfoService authorityInfoService;
    private final AuthorityInfoRepository authorityInfoRepository;

    public AuthorityInfoResource(AuthorityInfoService authorityInfoService, AuthorityInfoRepository authorityInfoRepository) {
        this.authorityInfoService = authorityInfoService;
        this.authorityInfoRepository = authorityInfoRepository;
    }

    /**
     * 新增权限
     * POST  /authorityInfos : Create a new authorityInfo.
     */
    @PostMapping("/authorityInfos")
    @Timed
    public BaseDTO createAuthorityInfo(@RequestBody AuthorityInfoDTO authorityInfoDTO) throws URISyntaxException {
        log.debug("REST request to save AuthorityInfo : {}", authorityInfoDTO);
        if (authorityInfoDTO.getId() != null) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("permission_exist");
        }
        if(authorityInfoRepository.findByPermission(authorityInfoDTO.getPermission()).size()>0) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("permission_exist");
        }
        AuthorityInfoDTO result = authorityInfoService.save(authorityInfoDTO);
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * 修改权限
     * PUT  /authorityInfos : Updates an existing authorityInfo.
     */
    @PutMapping("/authorityInfos/{id}")
    @Timed
    public BaseDTO updateAuthorityInfo(@RequestBody AuthorityInfoDTO authorityInfoDTO,
                                       @PathVariable("id") String id )  {
        log.debug("REST request to update AuthorityInfo : {}", authorityInfoDTO);
        authorityInfoDTO.setId(id);
        if(authorityInfoRepository.findByPermissionAndId(authorityInfoDTO.getPermission(),authorityInfoDTO.getId()).size()>0) {
            return BaseDTO.createBaseDTO().setSuccess(BaseDTO.CODE_PARAM).setMessage("permission_exist");
        }
        AuthorityInfoDTO result = authorityInfoService.save(authorityInfoDTO);
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * 获取权限列表（不分页）
     * GET  /authorityInfos : get all the authorityInfos.
     *
     * @param keyWord   查询关键字
     * @return BaseDTO
     */
    @GetMapping("/authorityInfos")
    @Timed
    public BaseDTO getAllAuthorityInfos (@RequestParam(value = "keyWord",required = false) String keyWord) {
        log.debug("REST request to get all AuthorityInfos");
        String hsql = "";
        Map<String,Object> queryParams = new HashMap<>();
        if (keyWord != null) {
            hsql = " and name like :name ";
            queryParams.put("name","%"+keyWord+"%");
        }
        List<AuthorityInfoDTO> result = authorityInfoService.findAllList(hsql,queryParams);
        return BaseDTO.createBaseDTO().setFieldList(result);
    }


    /**
     * 根据id获取指定权限
     */
    @GetMapping("/authorityInfos/{id}")
    @Timed
    public BaseDTO getAuthorityInfo(@PathVariable String id) {
        log.debug("REST request to get AuthorityInfo : {}", id);
        AuthorityInfoDTO authorityInfoDTO = authorityInfoService.findOne(id);
        return BaseDTO.createBaseDTO().setData(authorityInfoDTO);
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/authorityInfos/{id}")
    @Timed
    public BaseDTO deleteAuthorityInfo(@PathVariable String id) {
        log.debug("REST request to delete AuthorityInfo : {}", id);
        authorityInfoService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 获取当前登录用户的权限列表（树状结构）
     * @autor wjf
     * @date 2017年8月7日 17:06:46
     */
    @GetMapping("/authorityInfos/currentUser")
    @Timed
    public BaseDTO getCurrentUserAuthorityInfoes() {
        List<AuthorityInfoDTO> result = authorityInfoService.findCurrentUserAuthorityInfoesWithTree();
        return BaseDTO.createBaseDTO().setFieldList(result);
    }

    /**
     * 根据权限id，查取下一级权限列表
     */
    @GetMapping("/authorityInfos/{id}/childAuthorityInfos")
    @Timed
    public BaseDTO getCurrentUserAuthorityInfoesById(@PathVariable String id){
        List<AuthorityInfoDTO> result = authorityInfoService.findCurrentUserChildAuthorityInfoesById(id);
        return BaseDTO.createBaseDTO().setFieldList(result);
    }
}
